package com.Jesse205.aidelua2;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.KeyEvent;
import com.androlua.LuaApplication;
import com.xiaoyv.editor.android.FreeScrollingTextField;
import com.xiaoyv.editor.android.YoyoNavigationMethod;
import com.xiaoyv.editor.common.ColorScheme;
import com.xiaoyv.editor.common.ColorSchemeDark;
import com.xiaoyv.editor.common.ColorSchemeLight;
import com.xiaoyv.editor.common.Document;
import com.xiaoyv.editor.common.DocumentProvider;
import com.xiaoyv.editor.common.Language;
import com.xiaoyv.editor.common.LanguageJava;
import com.xiaoyv.editor.common.Lexer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class JavaEditor extends FreeScrollingTextField {

    private boolean _isWordWrap;

    private Context mContext;

    private String _lastSelectedFile;

    private String fontDir = LuaApplication.getInstance().getLuaExtDir("fonts");
    //private String libDir = LuaApplication.getInstance().getLuaExtPath("android.jar");

    private int _index;

    @SuppressLint("StaticFieldLeak")
    public JavaEditor(final Context context) {
        super(context);
        mContext = context;
        setTypeface(Typeface.MONOSPACE);
        File df = new File(fontDir, "default.ttf");
        if (df.exists())
            setTypeface(Typeface.createFromFile(df));
        DisplayMetrics dm = context.getResources().getDisplayMetrics();

        float size = TypedValue.applyDimension(2, BASE_TEXT_SIZE_PIXELS, dm);
        setTextSize((int) size);
        setShowLineNumbers(true);
        setHighlightCurrentRow(true);
        setWordWrap(false);
        setAutoIndentWidth(2);
        Lexer.setLanguage(LanguageJava.getInstance());
        setNavigationMethod(new YoyoNavigationMethod(this));
        TypedArray array = mContext.getTheme().obtainStyledAttributes(new int[]{
                                                                          android.R.attr.colorBackground,
                                                                          android.R.attr.textColorPrimary,
                                                                          android.R.attr.textColorHighlight,
                                                                      });
        int textColor = array.getColor(1, 0xFF00FF);
        int textColorHighlight = array.getColor(2, 0xFF00FF);
        array.recycle();
        setTextColor(textColor);
        setTextHighlightColor(textColorHighlight);
        /*
         new AsyncTask<String, String, String[]>(){
         @Override
         protected String[] doInBackground(String... strings) {
         String[] cls = LuaUtil.getAllName(context, libDir);
         for (int i = 0; i < cls.length; i++) {
         String cl = cls[i];
         int d = cl.lastIndexOf("$");
         if(d<0)
         d = cl.lastIndexOf(".");
         if(d>0)
         cls[i]=cl.substring(d);
         }
         return cls;
         }

         @Override
         protected void onPostExecute(String[] cls) {
         addNames(cls);
         }
         }.execute();*/
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        // TODO: Implement this method
        super.onLayout(changed, left, top, right, bottom);
        if (_index != 0 && right > 0) {
            moveCaret(_index);
            _index = 0;
        }
    }

    public void setDark(boolean isDark) {
        if (isDark)
            setColorScheme(new ColorSchemeDark());
        else
            setColorScheme(new ColorSchemeLight());
    }

    public void setLanguage(Language language) {
        Lexer.setLanguage(language);
    }


    public void setKeywordColor(int color) {
        getColorScheme().setColor(ColorScheme.ColorType.KEYWORD, color);
    }

    public void setStringColor(int color) {
        getColorScheme().setColor(ColorScheme.ColorType.LITERAL, color);
    }

    public void setCommentColor(int color) {
        getColorScheme().setColor(ColorScheme.ColorType.COMMENT, color);
    }

    public void setBackgoudColor(int color) {
        getColorScheme().setColor(ColorScheme.ColorType.BACKGROUND, color);
    }

    public void setTextColor(int color) {
        getColorScheme().setColor(ColorScheme.ColorType.FOREGROUND, color);
    }

    public void setTextHighlightColor(int color) {
        getColorScheme().setColor(ColorScheme.ColorType.SELECTION_BACKGROUND, color);
    }

    public void setSymbolColor(int color) {
        getColorScheme().setColor(ColorScheme.ColorType.SYMBOL, color);
    }
    
    public void setNumberColor(int color) {
        getColorScheme().setColor(ColorScheme.ColorType.NUMBER, color);
    }
    
    public void setOperatorColor(int color) {
        getColorScheme().setColor(ColorScheme.ColorType.OPERATOR, color);
    }
    
    public String getSelectedText() {
        // TODO: Implement this method
        return documentProvider.subSequence(getSelectionStart(), getSelectionEnd() - getSelectionStart()).toString();
    }

    @Override
    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
        final int filteredMetaState = event.getMetaState() & ~KeyEvent.META_CTRL_MASK;
        if (KeyEvent.metaStateHasNoModifiers(filteredMetaState)) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_A:
                    selectAll();
                    return true;
                case KeyEvent.KEYCODE_X:
                    cut();
                    return true;
                case KeyEvent.KEYCODE_C:
                    copy();
                    return true;
                case KeyEvent.KEYCODE_V:
                    paste();
                    return true;
                case KeyEvent.KEYCODE_L:
                    format();
                    return true;
            }
        }
        return super.onKeyShortcut(keyCode, event);
    }



    @Override
    public void setWordWrap(boolean enable) {
        // TODO: Implement this method
        _isWordWrap = enable;
        super.setWordWrap(enable);
    }

    public DocumentProvider getText() {
        return createDocumentProvider();
    }

    public void setText(CharSequence c) {
        //TextBuffer text=new TextBuffer();
        Document doc = new Document(this);
        doc.setWordWrap(_isWordWrap);
        doc.setText(c);
        setDocumentProvider(new DocumentProvider(doc));
        //doc.analyzeWordWrap();
    }

    public void insert(int idx, String text) {
        selectText(false);
        moveCaret(idx);
        paste(text);
        //_hDoc.insert(idx,text);
    }

    public void setText(CharSequence c, boolean isRep) {
        replaceText(0, getLength() - 1, c.toString());
    }

    public void setSelection(int index) {
        selectText(false);
        if (!hasLayout())
            moveCaret(index);
        else
            _index = index;
    }

    public void gotoLine(int line) {
        if (line > documentProvider.getRowCount()) {
            line = documentProvider.getRowCount();
        }
        int i = getText().getLineOffset(line - 1);
        setSelection(i);
    }

    public void undo() {
        DocumentProvider doc = createDocumentProvider();
        int newPosition = doc.undo();

        if (newPosition >= 0) {
            setEdited(true);
            reSpan();
            selectText(false);
            moveCaret(newPosition);
            invalidate();
        }

    }

    public void redo() {
        DocumentProvider doc = createDocumentProvider();
        int newPosition = doc.redo();

        if (newPosition >= 0) {
            setEdited(true);

            reSpan();
            selectText(false);
            moveCaret(newPosition);
            invalidate();
        }
    }

    public String getFilePath() {
        return _lastSelectedFile;
    }

    public void open(String filename) throws IOException {
        _lastSelectedFile = filename;
        BufferedReader reader = new BufferedReader(new FileReader(filename));
        StringBuilder buf = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null)
            buf.append(line).append("\n");
        if (buf.length() > 1)
            buf.setLength(buf.length() - 1);
        setText(buf);
        /*
         File inputFile = new File(filename);
         _inputtingDoc = new Document(this);
         _inputtingDoc.setWordWrap(this.isWordWrap());
         ReadTask _taskRead = new ReadTask(this, inputFile);
         _taskRead.start();*/
    }

    public boolean save() throws IOException {
        return save(_lastSelectedFile);
    }

    public boolean save(String filename) throws IOException {
        if (filename == null)
            return true;
        File outputFile = new File(filename);

        if (outputFile.exists()) {
            if (!outputFile.canWrite()) {
                return false;
            }
        }

        BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
        writer.write(getText().toString());
        writer.close();
        return true;
    }

}
